
import { ReactNode, useMemo } from 'react';
import { useEffect, useRef, useState } from 'react';
import { useRecoilValue } from 'recoil';
import { mouse } from '../../store/mouse';
import styles from './index.module.scss';
interface AppProp{
    children?: ReactNode, 
    print?: boolean,
    bg:string,
    tip:string,
}
const baseMargin = 8

const AppUi: React.FC<AppProp> = ({ children, print ,bg,tip}) => {
    const [mousex,] = useRecoilValue(mouse)
    const [initX, setInitX] = useState(0)
    const [width, setWidth] = useState(0)
    const ref: any = useRef()
    const { scale, transition } = useMemo(() => {
        let scale = 1, newMargin, transition;
        transition = "all 0s "
        if (initX === 0 || mousex === 0) {
            return { gapX: null, scale, newMargin }
        }

        const gapX = Math.abs(mousex - (initX + (width / 2)))

        if (gapX <= 240) {

            const addscale = (40 - gapX / 6) * 0.01
            scale += addscale
            if (print) {
                console.log(scale);
            }


        } else {
            scale = 1
            transition = "all 0.3s ease"
        }
        return { gapX, scale, transition }
    }, [initX, print, mousex, width])
    useEffect(() => {
        const app: HTMLDivElement = ref.current
        setInitX(app.offsetLeft)
        setWidth(app.offsetWidth)
        app.onmousemove = () => {
            setInitX(app.offsetLeft)
            setWidth(app.offsetWidth)
        }
    }, [])
    return (
        <div
            className={styles.box}
            
            style={{
                // transform:`translateX(${scale}px) `,
                width: `${scale*50}px`,
                height: `${scale*50}px`,
                margin: `0 ${baseMargin}px`,
                transition: transition,
                backgroundImage:`url(${bg})`
            }}
            ref={ref}
        >
            {children}
            <div className={styles.tip}>
                {tip}
            </div>
        </div>
    )
}

const App: React.FC<AppProp> = (props) => {
    return (
        <>
            <AppUi {...props}>
                {props.children}
            </AppUi>
        </>
    )
}

export default App